<?php
namespace payment\service;

use herosphp\bean\Beans;
use herosphp\core\Log;
use payment\models\TradeDetailVo;
use payment\service\interfaces\IBankLogService;
use common\service\CommonService;
use herosphp\core\Loader;
use payment\utils\SerialNumberUtils;
use user\service\interfaces\IUserService;

Loader::import('payment.service.interfaces.IBankLogService');

/**
 * 银行附属账户流水服务接口实现
 * @package payment\service
 * @author yangjian<yangjian102621@gmail.com>
 */
class BankLogService extends CommonService implements IBankLogService {

    const LOGFILE = '.bankLog'; //日志文件

    /**
     * 抓取用户附属账户银行流水, 如果没有传入用户ID，则抓取所有的流水
     * @param string $userid 用户ID
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return mixed
     */
    public function addUserBankLogs($userid=null, $startDate=null, $endDate=null)
    {
        $userService = Beans::get('user.user.service');
        if ( $userid == null ) { //分页抓取流水
            $total = $userService->count();
            $page = 1;
            $pagesize = 20;
            $offset = 0;
            while ( $offset < $total ) {
                $users = $userService->limit($page, $pagesize)->find();
                foreach ( $users as $value ) {
                    $this->addOneBankLogs($value, $startDate, $endDate);
                }
                $page++;
                $offset += $pagesize;
            }
        } else {
            $user = $userService->getItem($userid);
            $this->addOneBankLogs($user,$startDate, $endDate);
        }
        return true;
    }

    /**
     * 抓取某个用户的银行流水
     * @param $user
     * @param $startDate
     * @param $endDate
     */
    protected function addOneBankLogs($user,$startDate=null, $endDate=null) {

        //没有签约的直接不抓取
        if ( $user['sign_status'] != IUserService::SIGN_STATUS_SIGNED ) return;
        $paywayService = Beans::get('payment.payway.service');
        $payway = $paywayService->getItem($user['payway']);
        if ( $startDate == null ) $startDate = date('Ymd');
        if ( $endDate == null ) $endDate = date('Ymd');
        
        $vo = new TradeDetailVo();
        $vo->setBankName($payway['key']);
        $vo->setRequestNumber(SerialNumberUtils::generate($payway['serial_prefix']));
        $vo->setAccount($user['virtual_account']);
        $vo->setBeginDate($startDate);
        $vo->setEndDate($endDate);
        $service = Beans::get("payment.payment.service");
        $res = $service->tradedetail($vo);

        if ( $res == false ) return;
        foreach ( $res['records'] as $key => $value ) {
            //流水号去重，已经抓过的流水不再抓取
            if ( $this->getModelDao()->count(array('serial_no' => $value['paymentNumber'])) > 0 ) {
                continue;
            }
            $tmp = array();
            $tmp['serial_no'] = $value['paymentNumber'];
            $tmp['virtual_account'] = $res['account'];
            if ( $value['loanSign'] == 1 ) { //支出
                $tmp['loan_sign'] = '-';
            } elseif ( $value['loanSign'] == 2 ) { //收入
                $tmp['loan_sign'] = '+';
            }
            $tmp['oppo_acc'] = $value['oppoAccno'];
            $tmp['oppo_name'] = $value['oppoName'];
            $tmp['amount'] = $value['amount'];
            $tmp['usable'] = $value['usableMoney'];
            $tmp['payway'] = $value['businessInfo'];
            $tmp['dealtime'] = $value['tradeDate'];
            $tmp['addtime'] = date('Y-m-d H:i:s');
            $isOffline = 1;
            /**
             * 判断是否线下交易,除去以下三种情况都可以算做是线下转账
             * 1. 入金，附属账户之间转账
             * 2. 自己充值
             * 3. 自己提现（支出）
             */
            if ( isVirtualAccount($value['oppoAccno']) ) $isOffline = 0;
            if ( $value['oppoAccno'] == $user['card_no'] ) $isOffline = 0;
            if ( $value['loanSign'] == 1 ) $isOffline = 0;

            $tmp['is_offline'] = $isOffline;
            if ( !$this->getModelDao()->add($tmp) ) {
                Log::info("抓取流水失败，流水号：{$value['paymentNumber']}", self::LOGFILE);
            } else {
                Log::info("抓取流水成功，流水号：{$value['paymentNumber']}", self::LOGFILE);
            }
        }
    }

}
